package de.zainodis.authorlist.ui;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;

/**
 * Reacts to navigation related changes. Each tab should have it's own instance
 * of this listener.
 * 
 * @author zainodis
 * 
 * @param <T>
 */
public class NavigationTabListener<T extends Fragment> implements ActionBar.TabListener {
   private Fragment fragment;
   private final Activity activity;
   private final String tag;
   private final Class<T> type;

   /**
    * Constructor used each time a new tab is created.
    * 
    * @param activity
    *           The host Activity, used to instantiate the fragment.s
    * @param tag
    *           The identifier tag for the fragment.
    * @param type
    *           The fragment's Class, used to instantiate the fragment.
    */
   public NavigationTabListener(Activity activity, String tag, Class<T> type) {
	 this.activity = activity;
	 this.tag = tag;
	 this.type = type;
   }

   public void onTabSelected(Tab tab, FragmentTransaction transaction) {
	 /*
	  * The fragment which has been added to this listener may have been
	  * replaced (can be the case for lists when drilling down), but if the tag
	  * has been retained, we should find the actual fragment that was showing
	  * in this tab before the user switched to another.
	  */
	 Fragment currentlyShowing = activity.getFragmentManager().findFragmentByTag(tag);

	 // Check if the fragment is already initialised
	 if (currentlyShowing == null) {
	    // If not, instantiate and add it to the activity
	    fragment = Fragment.instantiate(activity, type.getName());
	    transaction.add(android.R.id.content, fragment, tag);
	 } else {
	    // If it exists, simply attach it in order to show it
	    transaction.attach(currentlyShowing);
	 }
   }

   public void onTabUnselected(Tab tab, FragmentTransaction fragmentTransaction) {
	 /*
	  * The fragment which has been added to this listener may have been
	  * replaced (can be the case for lists when drilling down), but if the tag
	  * has been retained, we should find the actual fragment that's currently
	  * active.
	  */
	 Fragment currentlyShowing = activity.getFragmentManager().findFragmentByTag(tag);
	 if (currentlyShowing != null) {
	    // Detach the fragment, another tab has been selected
	    fragmentTransaction.detach(currentlyShowing);
	 } else if (this.fragment != null) {
	    fragmentTransaction.detach(fragment);
	 }
   }

   public void onTabReselected(Tab tab, FragmentTransaction fragmentTransaction) {
	 // This tab is already selected
   }

}
